package minio

import (
	"net/http"
	"oa-rest/common"
	"oa-rest/config"

	"github.com/gin-gonic/gin"
)

// CreateBucketRequest 创建bucket请求
type CreateBucketRequest struct {
	BucketName string `json:"bucketName" binding:"required"`
	Public     bool   `json:"public"`
}

// CreateBucketHandler 创建bucket
func CreateBucketHandler(c *gin.Context) {
	var req CreateBucketRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请求参数错误: " + err.Error(),
			"data":    nil,
		})
		return
	}

	// 检查bucket名称是否合法
	if !isValidBucketName(req.BucketName) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "bucket名称不合法，只能包含小写字母、数字、连字符和点",
			"data":    nil,
		})
		return
	}

	// 检查是否为系统保留的bucket
	//if isSystemBucket(req.BucketName) {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code":    400,
	//		"message": "不能创建系统保留的bucket名称: " + req.BucketName,
	//		"data":    nil,
	//	})
	//	return
	//}

	// 创建新的MinIO客户端连接到指定的bucket
	err := common.CreateBucket(req.BucketName, req.Public)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "创建bucket失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "创建bucket成功",
		"data": gin.H{
			"bucketName": req.BucketName,
			"public":     req.Public,
			"endpoint":   "http://" + config.MinioEndpoint + "/" + req.BucketName,
		},
	})
}

// 辅助函数：检查bucket名称是否合法
func isValidBucketName(bucketName string) bool {
	if len(bucketName) < 3 || len(bucketName) > 63 {
		return false
	}

	// 只能包含小写字母、数字、连字符、下划线和点
	for _, char := range bucketName {
		if !((char >= 'a' && char <= 'z') ||
			(char >= '0' && char <= '9') ||
			char == '-' || char == '_' || char == '.') {
			return false
		}
	}

	// 不能以连字符、下划线或点开头或结尾
	if bucketName[0] == '-' || bucketName[0] == '_' || bucketName[0] == '.' ||
		bucketName[len(bucketName)-1] == '-' || bucketName[len(bucketName)-1] == '_' || bucketName[len(bucketName)-1] == '.' {
		return false
	}

	return true
}

// 辅助函数：检查是否为系统保留bucket（创建时不能使用这些名称）
func isSystemBucket(bucketName string) bool {
	systemBuckets := []string{"test", "documents", "meeting"}
	for _, b := range systemBuckets {
		if b == bucketName {
			return true
		}
	}
	return false
}
